
import { PureComponent } from "react"
// import store from '../store'
import { StoreContext } from './StoreContext'

/**
 * 
 * @param {*} mapStateToProps 
 * @param {*} mapDispatchToProps 
 * @returns  返回函数 高阶函数
 */
export function connect (mapStateToProps, mapDispatchToProps) {

  return function (WrapperComponent) {
    class NewComponent extends PureComponent {
      constructor(props,context) {
        super(props);
        this.state = mapStateToProps(context.getState())
      }
      componentDidMount () {
        this.unsubscribe = this.context.subscribe(() => {
          // 强制全部更新
          // this.forceUpdate()
          // 优化
          this.setState(mapStateToProps(this.context.getState()))
        })
      }
      componentWillUnmount () {
        this.unsubscribe.unsubscribe();
      }
      render () {
        // 获取 组件传参过来的state 和 dispatch
        const state = mapStateToProps(this.context.getState());
        const dispatchObj = mapDispatchToProps(this.context.dispatch);

        return <WrapperComponent {...this.props} {...state} {...dispatchObj} />
      }
    }
    NewComponent.contextType = StoreContext;
    return NewComponent;
  }
}
// export default connect